﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;

namespace BLL
{
  public class OrderBLL
  {
    public List<Order> GetAll()
    {
      using (var data = new DigitalColorCMSDataContext(_Global.StringConnect))
      {
        return data.Orders.OrderByDescending(p => p.DateSend).ToList();
      }
    }
    public List<Order> GetByStatus(bool status)
    {
      using (var data = new DigitalColorCMSDataContext(_Global.StringConnect))
      {
        return data.Orders.Where(p => p.Status == status).OrderByDescending(p => p.DateSend).ToList();
      }
    }
    public Order GetById(int id)
    {
      using (var data = new DigitalColorCMSDataContext(_Global.StringConnect))
      {
        return data.Orders.Where(p => p.Id == id).FirstOrDefault();
      }
    }
    public List<Order> GetByUserId(int userId)
    {
      using (var data = new DigitalColorCMSDataContext(_Global.StringConnect))
      {
        return data.Orders.Where(p => p.IdCustomer == userId).OrderByDescending(p => p.Id).ToList();
      }
    }
    public int GetMaxId()
    {
      using (var data = new DigitalColorCMSDataContext(_Global.StringConnect))
      {
        Order obj = data.Orders.OrderByDescending(p => p.Id).FirstOrDefault();
        return (obj == null ? 1 : obj.Id + 1);
      }
    }
    public void Add(Order obj)
    {
      using (var data = new DigitalColorCMSDataContext(_Global.StringConnect))
      {
        data.Orders.InsertOnSubmit(obj);
        data.SubmitChanges();
      }
    }

    public void SetStatus(int id, bool status)
    {
      using (var data= new DigitalColorCMSDataContext(_Global.StringConnect))
      {
        Order obj = data.Orders.Where(p => p.Id == id).FirstOrDefault();
        if (obj != null)
        {
          obj.Status = status;
          data.SubmitChanges();
        }
      }
    }

    public void Delete(int id)
    {
      using (var data = new DigitalColorCMSDataContext(_Global.StringConnect))
      {
        Order obj = data.Orders.Where(p => p.Id == id).FirstOrDefault();
        if (obj != null)
        {
          data.Orders.DeleteOnSubmit(obj);
          data.SubmitChanges();
        }
      }
    }

    public void Read(int id)
    {
      using (var data = new DigitalColorCMSDataContext(_Global.StringConnect))
      {
        Order obj = data.Orders.Where(p => p.Id == id).FirstOrDefault();
        obj.IsRead = true;

        data.SubmitChanges();
      }
    }

    public void DeleteByCustomerId(int customerId)
    {
      using (var data = new DigitalColorCMSDataContext(_Global.StringConnect))
      {
        List<Order> list = data.Orders.Where(p => p.IdCustomer == customerId).ToList();
        if (list.Count > 0)
        {
          data.Orders.DeleteAllOnSubmit(list);
          data.SubmitChanges();
        }
      }
    }
  }
}
